//
// Created by grg on 2020/8/3.
// Copyright (c) 2020 龚任根. All rights reserved.
//

#ifndef TEST_CPP_PROJECT_LTRBTTVIEW_H
#define TEST_CPP_PROJECT_LTRBTTVIEW_H

#include "IBlockPart.h"

class LTRBTTView : public IBlockPart {

private:
    SDL_Surface *img = nullptr;
    SDL_Texture *imgTexture = nullptr;
    SDL_Rect *srcRect = nullptr;
    SDL_Rect *targetRect = nullptr;

public:
    LTRBTTView() {
        img = IMG_Load(imagePath("coins.png"));
        imgTexture = SDL_CreateTextureFromSurface(gContext->getRender(), img);

        //源图 的哪一部分
        srcRect = nullptr;

        //画布的 哪一部分
        targetRect = new SDL_Rect{0, 0, 50, 50};

    }

    ~LTRBTTView() {
        SDL_DestroyTexture(imgTexture);
        SDL_FreeSurface(img);
        delete srcRect;
        delete targetRect;
    }

public:
    void updateTargetXY(int x,int y){
        targetRect->x = x;
        targetRect->y = y;
    }

private:
    bool ltrlRight = true;
    bool ltrlBottom = true;
    void ltrbAutoMove(SDL_Rect &rect) {
        if (ltrlRight) {
            rect.x++;
            if (rect.x + rect.w > Window_Width) {
                ltrlRight = false;
            }
        } else {
            rect.x--;
            if (rect.x <= 0) {
                ltrlRight = true;
            }
        }

        if (ltrlBottom) {
            rect.y++;
            if (rect.y + rect.h > Window_Height) {
                ltrlBottom = false;
            }
        } else {
            rect.y--;
            if (rect.y <= 0) {
                ltrlBottom = true;
            }
        }

    }

    void event(const SDL_Event *event) override {
        if (event->type == SDL_KEYDOWN) {
            switch (event->key.keysym.sym) {
                case SDLK_w:
                    targetRect->y -= 5;
                    break;
                case SDLK_s:
                    targetRect->y += 5;
                    break;
                case SDLK_a:
                    targetRect->x -= 5;
                    break;
                case SDLK_d:
                    targetRect->x += 5;
                    break;
                default:
                    break;
            }
        }

    }

    void draw() override {
        updateUI(imgTexture, srcRect, targetRect);
    }

protected:
    void update() override {
        ltrbAutoMove(*targetRect);
    }


public:
    void kill() override {
        delete this;
    }

};


#endif //TEST_CPP_PROJECT_LTRBTTVIEW_H
